<template>
  <LoginFormTitle v-show="getShow" class="enter-x" />
  <Form
    style="padding: 1rem 5rem"
    class="p-4 enter-x"
    :model="formData"
    :rules="rules"
    ref="formRef"
    v-show="getShow"
    @keypress.enter="handleLogin"
  >
    <FormItem name="account" class="enter-x">
      <Input
        size="large"
        v-model:value="formData.account"
        :placeholder="t('sys.login.userAccount')"
        class="fix-auto-fill"
      />
    </FormItem>
    <FormItem name="password" class="enter-x">
      <InputPassword
        size="large"
        visibilityToggle
        v-model:value="formData.password"
        :placeholder="t('sys.login.password')"
      />
    </FormItem>
    <FormItem name="accountName" class="enter-x">
      <Input
        size="large"
        v-model:value="formData.accountName"
        :placeholder="t('sys.login.userName')"
        class="fix-auto-fill"
      />
    </FormItem>

    <FormItem name="generateCode" class="enter-x login-code">
      <Input
        size="large"
        visibilityToggle
        v-model:value="formData.generateCode"
        :placeholder="t('sys.login.code')"
      />
      <div @click="getCode" style="display: inline-block">
        <img :src="img" alt="" />
      </div>
    </FormItem>

    <!-- <ARow class="enter-x">
      <ACol :span="12">
        <FormItem>

          <Checkbox v-model:checked="rememberMe" size="small">
            {{ t('sys.login.rememberMe') }}
          </Checkbox>
        </FormItem>
      </ACol>
      <ACol :span="12">
        <FormItem :style="{ 'text-align': 'right' }">

          <Button type="link" size="small" @click="setLoginState(LoginStateEnum.RESET_PASSWORD)">
            {{ t('sys.login.forgetPassword') }}
          </Button>
        </FormItem>
      </ACol>
    </ARow> -->

    <FormItem class="enter-x">
      <Button type="primary" size="large" block @click="handleLogin" :loading="loading">
        {{ t('sys.login.loginButton') }}
      </Button>
      <!-- <Button size="large" class="mt-4 enter-x" block @click="handleRegister">
        {{ t('sys.login.registerButton') }}
      </Button> -->
    </FormItem>
    <!-- <ARow class="enter-x">
      <ACol :md="8" :xs="24">
        <Button block @click="setLoginState(LoginStateEnum.MOBILE)">
          {{ t('sys.login.mobileSignInFormTitle') }}
        </Button>
      </ACol>
      <ACol :md="8" :xs="24" class="!my-2 !md:my-0 xs:mx-0 md:mx-2">
        <Button block @click="setLoginState(LoginStateEnum.QR_CODE)">
          {{ t('sys.login.qrSignInFormTitle') }}
        </Button>
      </ACol>
      <ACol :md="7" :xs="24">
        <Button block @click="setLoginState(LoginStateEnum.REGISTER)">
          {{ t('sys.login.registerButton') }}
        </Button>
      </ACol>
    </ARow> -->

    <!-- <Divider class="enter-x">{{ t('sys.login.otherSignIn') }}</Divider>

    <div class="flex justify-evenly enter-x" :class="`${prefixCls}-sign-in-way`">
      <GithubFilled />
      <WechatFilled />
      <AlipayCircleFilled />
      <GoogleCircleFilled />
      <TwitterCircleFilled />
    </div> -->
  </Form>
  <a-modal width="35%" v-model:visible="changePasswdVisible" title="修改密码" footer="">
    <Password
      page-title="首次登陆修改密码"
      @successPwd="successPwd"
      content="修改成功后自动进入系统！"
    />
  </a-modal>

  <a-modal width="25%" v-model:visible="authorityVisible" title="请选择角色" footer="">
    <div class="classStyle">
      <a-button
        type="primary"
        size="large"
        v-for="item in authorityList"
        @click="authorityClick(item)"
      >
        {{ item.roleName }}
      </a-button>
    </div>
  </a-modal>
</template>
<script lang="ts" setup>
import { reactive, ref, unref, computed, onMounted } from 'vue'

import { loginCode } from '/@/api/sys/user'
import { getInfoJsinfo } from '/@/api/system-manage/teacher-info'
import Password from '../password/index.vue'
import { Form, Select, Input, Button } from 'ant-design-vue'
import LoginFormTitle from './LoginFormTitle.vue'
import { useI18n } from '/@/hooks/web/useI18n'
import { useMessage } from '/@/hooks/web/useMessage'
import { useUserStore } from '/@/store/modules/user'
import { LoginStateEnum, useLoginState, useFormValid } from './useLogin'
import { message } from 'ant-design-vue'
//import { onKeyStroke } from '@vueuse/core';

import { useGlobSetting } from '/@/hooks/setting'
const globSetting = useGlobSetting()

const FormItem = Form.Item
const InputPassword = Input.Password
const { t } = useI18n()
const { notification, createMessage } = useMessage()
const userStore = useUserStore()
const authorityVisible = ref(false)

const { getLoginState } = useLoginState()
const formData = reactive<any>({
  account: '',
  password: '',
  generateCode: '',
  accountName: '',
  kmYear: null,
})

const rules = {
  account: [{ required: true, message: '请输入账号名称', trigger: 'blur' }],
  password: [{ required: true, message: '请输入账号密码', trigger: 'blur' }],
  userType: [{ required: true, message: '请选择账号类型', trigger: 'blur' }],
  generateCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
  accountName: [{ required: true, message: '请输入教师姓名', trigger: 'blur' }],
  kmYear: [
    { required: !/^admin$/i.test(formData.account), message: '请选择年份', trigger: 'blur' },
  ],
}

const formRef = ref()
const loading = ref(false)
const changePasswdVisible = ref(false)
// 验证码
const img = ref('')
const verifyCodeId = ref('')

const authorityClick = item => {
  userStore.setAuthorityItem(item)
  userStore.afterLoginAction(true)
  authorityVisible.value = false
}

const authorityList = computed(() => userStore.getAuthority)

const { validForm } = useFormValid(formRef)

const getShow = computed(() => unref(getLoginState) === LoginStateEnum.LOGIN)

const userInfo: any = ref({})

async function handleLogin() {
  formRef.value.validate().then(async () => {
    const formdata = await validForm()
    if (!formdata) return
    loading.value = true
    try {
      const res: any = await userStore.login({
        pwd: formdata.password,
        account: formdata.account,
        verifyCode: formdata.generateCode,
        verifyCodeId: verifyCodeId.value,
        jsxm: formdata.accountName,
        device: globSetting.device,
      })
      if (res.code == 200) {
        userInfo.value = res.data
        if (res.data) {
          if (res.data.pwdUpdateFlag === false) {
            //上个版本需要修改密码这个版本先按设计图来做
            changePasswdVisible.value = true
          } else {
            nextLoginFun()
          }
        }
      } else {
        getCode()
        if (res.message) message.error(res.message)
      }
    } catch (error) {}
    loading.value = false
  })
}

/**
 * 修改密码成功
 */
function successPwd() {
  changePasswdVisible.value = false
  nextLoginFun()
}

/**
 *
 * 需改密码后的操作
 */
async function nextLoginFun() {
  if (userInfo.value.accountType === 'ADMIN') {
    userStore.afterLoginAction(true)
  } else {
    const { code, data } = await getInfoJsinfo({ account: userInfo.value.account })
    if (code == 200) {
      userStore.setAuthority(data)
      if (data.length == 1) {
        userStore.setAuthorityItem(data[0])
        userStore.afterLoginAction(true)
      } else if (data.length > 1) {
        if (authorityList.value.length > 0) {
          authorityVisible.value = true
          notification.success({
            message: t('sys.login.loginSuccessTitle'),
            description: `${t('sys.login.loginSuccessDesc')}: ${
              userInfo.value.jsxm || userInfo.value.jsgs
            }`,
            duration: 3,
          })
        }
      } else {
        createMessage.error('暂无权限,请联系管理员！')
      }
    }
  }
}

const getCode = async () => {
  try {
    let res = await loginCode({ expireSeconds: 86400 })
    verifyCodeId.value = res.data.verifyCodeId
    img.value = res.data.imageBase64Data
  } catch (err) {
    console.error(err)
    message.error('获取验证码失败')
  }
}

onMounted(async () => {
  getCode()
})
</script>
<style lang="less">
.login-code {
  .ant-form-item-control-input-content {
    display: flex;
  }

  img {
    // width: 150px;
    height: 100% !important;
  }
}

.userType {
  .ant-select-selector {
    height: 40px !important;
    display: flex;
    align-items: center;
  }

  .ant-select-selection-placeholder {
    line-height: 40px !important;
    font-size: 15px;
  }
}

.classStyle {
  flex-wrap: wrap;
  padding: 20px;
  button {
    display: block;
    margin: 20px auto;
    width: 50%;
  }
}
</style>
